#include "SyncEvent.h"


CSyncEvent::CSyncEvent(BOOL bInitiallyOwn/* = FALSE*/, BOOL bManualReset/* = FALSE*/)
	:m_bStatus(bInitiallyOwn)
	, m_bManual(bManualReset)
{
}


CSyncEvent::~CSyncEvent()
{
}

BOOL CSyncEvent::Wait(int millisecs /*= -1*/)
{
	BOOL bWait(TRUE);
	std::unique_lock<std::mutex> _lock(m_mutex);

	if (millisecs < 0)
	{
		while (!m_bStatus)
		{
			m_cv.wait(_lock);
		}

	}
	else
	{
		while (!m_bStatus)
		{
			bWait = TRUE;
			std::cv_status status = m_cv.wait_for(_lock, std::chrono::milliseconds(millisecs));
			if (std::cv_status::timeout == status)
			{
				bWait = FALSE;
			}
			break;
		}

	}

	if (bWait && !m_bManual)
	{
		m_bStatus = FALSE;
	}
	return bWait;
}


void CSyncEvent::SetEvent()
{
	std::unique_lock<std::mutex> _lock(m_mutex);
	m_bStatus = TRUE;
	if (m_bManual)
	{
		m_cv.notify_all();
	}
	else
	{
		m_cv.notify_one();
	}
}

void CSyncEvent::ResetEvent()
{
	std::unique_lock<std::mutex> _lock(m_mutex);
	m_bStatus = FALSE;
}
